/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.actions;

import com.softwarecraftsmen.orogeny.buildEnvironments.BuildEnvironment;
import com.softwarecraftsmen.orogeny.buildLogs.BuildLog;
import static com.softwarecraftsmen.orogeny.buildLogs.Verbosity.Summary;
import com.softwarecraftsmen.orogeny.execution.SuccessOrFailure;
import com.softwarecraftsmen.orogeny.properties.Evaluatable;
import com.softwarecraftsmen.orogeny.properties.PropertyName;
import com.softwarecraftsmen.orogeny.properties.ObjectArrayAdapterEvaluatable;
import com.softwarecraftsmen.orogeny.properties.StringAdapterEvaluatable;
import org.jetbrains.annotations.NotNull;

import java.io.StringWriter;
import java.util.Set;

public class EchoAction extends AbstractAction
{
	private final Evaluatable evaluatable;
	private final String describeWhatWeDo;

	private EchoAction(final @NotNull Evaluatable evaluatable)
	{
		this(evaluatable, "echo");
	}

	private EchoAction(final @NotNull Evaluatable evaluatable, final @NotNull String describeWhatWeDo)
	{
		this.evaluatable = evaluatable;
		this.describeWhatWeDo = describeWhatWeDo;
	}

	@NotNull
	public String describeWhatWeDo()
	{
		return describeWhatWeDo;
	}

	@NotNull
	public SuccessOrFailure execute(final @NotNull BuildLog buildLog, final @NotNull BuildEnvironment buildEnvironment)
	{
		buildLog.writeMessage(Summary, evaluatable.evaluate(buildEnvironment));
		return SuccessOrFailure.Success;
	}

	@NotNull
	public static EchoAction echo(final @NotNull PropertyName propertyName)
	{
		return new EchoAction(propertyName);
	}

	@NotNull
	public static EchoAction echo(final @NotNull String text)
	{
		return new EchoAction(new StringAdapterEvaluatable(text));
	}

	@NotNull
	public static EchoAction echo(final @NotNull Object... objects)
	{
		return new EchoAction(new ObjectArrayAdapterEvaluatable(objects));
	}

	@NotNull
	public static EchoAction echoProperties()
	{
		return new EchoAction(new Evaluatable()
		{
			@NotNull
			public String evaluate(final @NotNull BuildEnvironment buildEnvironment)
			{
				final Set<PropertyName> sorted = buildEnvironment.allPropertyNames();
				final StringWriter writer = new StringWriter();
				for (PropertyName propertyName : sorted)
				{
					writer.write(propertyName.toString());
					writer.write(" = ");
					writer.write(buildEnvironment.getProperty(propertyName).evaluate(buildEnvironment));
					writer.write('\n');
				}
				return writer.toString();
			}
		}, "echoProperties");
	}
}
